package com.ztom.daily.n2022.m4;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 最小高度树
 * <p>
 * https://leetcode-cn.com/problems/minimum-height-trees/
 *
 * @author ZhangTao
 */
public class Day06FindMinHeightTrees {

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        if (n == 1) {
            res.add(0);
            return res;
        }

        // 记录每个节点的度
        int[] degree = new int[n];
        // 记录每个节点的相邻节点
        List<Integer>[] childList = new List[n];
        for (int i = 0; i < n; i++) {
            childList[i] = new ArrayList<>();
        }
        // 填充相邻节点
        for (int[] edge : edges) {
            childList[edge[0]].add(edge[1]);
            childList[edge[1]].add(edge[0]);
            degree[edge[0]]++;
            degree[edge[1]]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            // 找到度为 1 的节点
            if (degree[i] == 1) {
                queue.offer(i);
            }
        }

        int remainNode = n;
        while (remainNode > 2) {
            int size = queue.size();
            remainNode -= size;
            for (int i = 0; i < size; i++) {
                int cur = queue.poll();
                for (Integer child : childList[cur]) {
                    degree[child]--;
                    if (degree[child] == 1) {
                        queue.offer(child);
                    }
                }
            }
        }

        while (!queue.isEmpty()) {
            res.add(queue.poll());
        }
        return res;
    }
}
